﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ChildWindow
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            HwndSource.FromHwnd(new WindowInteropHelper(this).Handle).AddHook(HwndSourceHook);
        }

        protected IntPtr HwndSourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            switch (msg)
            {
                case User32.WM_Minimal:
                    this.WindowState = WindowState.Minimized;
                    break;
                case User32.WM_Normal:
                    this.WindowState = WindowState.Normal;
                    break;
                case User32.WM_Exit:
                    this.Close();
                    break;
                case User32.WM_ShowInTaskBar:
                    this.ShowInTaskbar = false;
                    break;
                case User32.WM_Size:
                    this.Width = (double)wParam;
                    this.Height = (double)lParam;
                    break;
                case User32.WM_Pos:
                    this.Left = LOWORD((uint)lParam);
                    this.Top = HIWORD((uint)lParam);
                    break;
            }

            return IntPtr.Zero;
        }


        private ushort LOWORD(uint value)
        {
            return (ushort)(value & 0xFFFF);
        }

        private ushort HIWORD(uint value)
        {
            return (ushort)(value >> 16);
        }
    }
}
